/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { ViewTreeNode, Stmt, ArkMethod, ArkInvokeStmt, ArkAssignStmt, Local } from 'arkanalyzer';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback, MethodMatcher } from '../../Index';
import { ViewTreeTool } from '../../utils/checker/ViewTreeTool';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InvalidPropertyCheck');
const viewTreeTool = new ViewTreeTool();
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/invalid-property-check.md',
    description: 'Flex properties are only effective in the direct child components of a Flex container, and should be detected and removed if used in non-Flex containers.'
};
const flexOnlyProperties = ['alignSelf', 'flexGrow', 'flexShrink', 'flexBasis', 'order', 'flexDirection', 'flexWrap', 'alignContent'];
export class InvalidPropertyCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS,
        hasViewTree: true
    };
    private mtdMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD,
        hasViewTree: true
    };

    public registerMatchers(): MatcherCallback[] {
        const matchClazzCb: MatcherCallback = {
            matcher: this.clsMatcher,
            callback: this.check
        };
        const matchMethodCb: MatcherCallback = {
            matcher: this.mtdMatcher,
            callback: this.check
        };
        return [matchClazzCb, matchMethodCb];
    }

    public check = (target: ArkClass | ArkMethod): void => {
        const viewTreeRoot = target.getViewTree()?.getRoot();
        if (!viewTreeRoot) {
            return;
        }
        this.traverseViewTree(viewTreeRoot);
    };

    private traverseViewTree(node: ViewTreeNode): void {
        // 处理节点不存在或已遍历的情况
        if (!node || viewTreeTool.hasTraverse(node)) {
            return;
        }
        const attributes = node.attributes;
        for (let key of attributes.keys()) {
            if (!flexOnlyProperties.includes(key)) {
                continue;
            }
            const name = node.parent?.name;
            if (!name || name === 'Flex') {
                continue;
            }
            const value = attributes.get(key);
            if (value && value instanceof Array) {
                const stmt = this.getStmtByValues(value[0]);
                this.reportIssue(stmt, key);
            }
        }
        // 递归遍历子节点
        for (let child of node.children) {
            this.traverseViewTree(child);
        }
    }

    private getStmtByValues(stmt: Stmt): Stmt | null {
        let declaringStmt: Stmt | null = null;
        if (stmt instanceof ArkInvokeStmt) {
            declaringStmt = stmt;
        }
        if (stmt instanceof ArkAssignStmt) {
            const leftOp = stmt.getLeftOp();
            if (leftOp instanceof Local) {
                declaringStmt = leftOp.getDeclaringStmt();
            }
        }
        return declaringStmt;
    }

    private reportIssue(stmt: Stmt | null, key: string): void {
        if (!stmt) {
            return;
        }
        const severity = this.rule.alert ?? this.metaData.severity;
        const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile();
        const originPosition = stmt.getOperandOriginalPosition(stmt.getDefAndUses().length - 1);
        if (!(arkFile && originPosition)) {
            return;
        }
        const lineNum = originPosition.getFirstLine();
        const endColunm = originPosition?.getFirstCol() - 1;
        const startColumn = endColunm - key.length;
        const filePath = arkFile.getFilePath();
        let defects = new Defects(lineNum, startColumn, endColunm, this.metaData.description, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}